package com.chuangke.aspect;

import com.chuangke.common.utils.ReflectionUtils;
import com.chuangke.common.utils.SecurityUtils;
import jodd.util.StringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * DAO切面，插入创建人，创建时间，修改人，修改时间
 * 
 * @author chuangke
 * @date Oct 29, 2018
 */
//@Aspect
//@Component
//@Configuration
public class DaoAspect {

	private static final Logger logger = LoggerFactory.getLogger(DaoAspect.class);

	private static final String[] CREATE_COLS_BY = { "createdBy", "updatedBy","commentBy" };
	private static final String[] CREATE_COLS_AT = { "createdAt", "updatedAt", "commentAt"};

	private static final String[] UPDATE_COLS_BY = { "updatedBy" };
	private static final String[] UPDATE_COLS_AT = { "updatedAt" };

	@Pointcut("execution(* com.chuangke.*.dao.*.update*(..))")
	public void daoUpdate() {
	}

	@Pointcut("execution(* com.chuangke.*.dao.*.insert*(..))")
	public void daoCreate() {
	}

	@Around("daoUpdate()")
	public Object doAroundUpdate(ProceedingJoinPoint pjp) throws Throwable {
		return doAroundAction(pjp, UPDATE_COLS_BY, UPDATE_COLS_AT);
	}

	@Around("daoCreate()")
	public Object doAroundCreate(ProceedingJoinPoint pjp) throws Throwable {
		return doAroundAction(pjp, CREATE_COLS_BY, CREATE_COLS_AT);
	}

	private Object doAroundAction(ProceedingJoinPoint pjp, String[] byCols, String[] atCols) throws Throwable {
		Object[] objects = pjp.getArgs();
		if (objects == null) {
			return pjp.proceed();
		}

		for (Object arg : objects) {
			setColValus(arg, byCols, atCols);
		}
		return pjp.proceed();
	}

	@SuppressWarnings("unchecked")
	private void setColValus(Object arg, String[] byCols, String[] atCols) {
		if(arg == null) return ;
		
		if (arg instanceof List) {
			List<Object> list = (List<Object>) arg;
			for (Object obj : list) {
				setColValus(obj, byCols, atCols);
			}
		}else {
			String username = SecurityUtils.getUserId();
			if(StringUtil.isNotEmpty(username)) {
				setColValus(arg, byCols, username);
			}
			setColValus(arg, atCols, new Date());
		}
	}

	private void setColValus(Object obj, String[] cols, Object value) {
		for (String col : cols) {
			try {
				if (ReflectionUtils.hasProperty(obj, col) ) {//&& StringUtils.isBlank(BeanUtils.getProperty(obj, col))
					BeanUtils.setProperty(obj, col, value);
				}
			} catch (Exception e) {
				logger.error("Dao设置字段信息出错:{}", e.getMessage());
			}
		}
	}

}
